package com.ruoyi.core.manager;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.RedisCacheKeyHelper;
import com.ruoyi.core.domain.ClientProductUser;
import com.ruoyi.core.mapper.ClientProductUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @Description:
 * @Company: 北京卡拉卡尔股份技术有限公司
 * @Author: Darren Ho
 * @Date: 10/28/2020 17:34
 */
@Component
public class ProductUserCookieResourceManager {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ClientProductUserMapper productUserMapper;

    public void setCookie(Long productUserId, String cookie) {

        redisCache.setCacheObject(RedisCacheKeyHelper.getProductUserCookieKey(productUserId), cookie);
    }

    public String getCookie(Long productUserId) {

        String configValue = redisCache.getCacheObject(RedisCacheKeyHelper.getProductUserCookieKey(productUserId));
        if (StringUtils.hasText(configValue)) {
            return configValue;
        }

        ClientProductUser clientProductUser = productUserMapper.selectClientProductUserById(productUserId);
        if (clientProductUser != null && StringUtils.hasText(clientProductUser.getCookie())) {

            setCookie(productUserId, clientProductUser.getCookie());
            return clientProductUser.getCookie();
        }
        return null;
    }

    public void clean(Long productUserId) {
        redisCache.deleteObject(RedisCacheKeyHelper.getProductUserCookieKey(productUserId));
    }
}
